<template>
	<view class="dynamic safe_area">
		<u-tabs :list="tabList" lineColor="#FF943C" :activeStyle="{
							color: '#FF943C',
						}" :inactiveStyle="{
							color: '#000000',fontSize:'14px'}" :scrollable="false" @click="handleTabClick" :current="tabCurrent"
			height="48"></u-tabs>
		<scroll-view :scroll-top="scrollTop" scroll-y="true" refresher-enabled="true" :refresher-triggered="triggered"
			@refresherrefresh="onRefresh" :refresher-threshold="50" @scrolltolower="scrolltolower"
			class="dynamic_scroll_view">
			<template v-if="tabCurrent === 0">
				<view class="circle_item" v-for="item in dataSouse" :key="item?.id" @click.stop="handleEdit(item)">
					<view class="circle_header">
						<image :src="item?.avatar" v-if="item?.avatar" class="circle_header_img"></image>
						<image src="http://qianxueapplet.suoeryun.com/child.png" v-else class="circle_header_img">
						</image>
						<view class="circle_header_right">
							<view class="circle_header_right_top">
								<text>{{item?.realname}}</text>
								<button @click.stop="handleDel(item)" class="circle_header_btn">
									<image src="http://qianxueapplet.suoeryun.com/delete.png">
									</image>
								</button>
							</view>
							<view class="circle_text">{{item?.content}}</view>
							<view class="circle_img">
								<template v-if="item?.dynamicType === '0'">
									<image :src="img" v-for="(img,index) in item?.images?.split(',')" :key="img"
										@click="handlePreview(item?.images,index)" mode="aspectFill">
									</image>
								</template>
								<template v-else-if="item?.dynamicType === '1'">
									<video :src="item?.images" @click="handleVideoPreview(item?.images)"
										:show-center-play-btn="false" :show-fullscreen-btn="false"
										:show-play-btn="false" :controls="false"
										:style="{height: Number(item.high)/3.5 + 'rpx',width:Number(item?.width)/3.5 +'rpx'}"></video>
								</template>
							</view>
							<view class="circle_header_right_bottom">
								<text>{{item?.fromToday}}编辑</text>
								<text v-if="item?.province">{{item?.province}}</text>
							</view>
							<view class="circle_tag" v-if="item?.activityName">
								<text>#{{item?.activityName}}</text>
							</view>
						</view>
					</view>
				</view>
			</template>
			<template v-else>
				<view class="circle_item" v-for="(item,index) in dataSousePublished" :key="item?.id">
					<view class="circle_header">
						<image :src="item?.avatar" v-if="item?.avatar" class="circle_header_img"></image>
						<image src="http://qianxueapplet.suoeryun.com/child.png" v-else class="circle_header_img">
						</image>
						<view class="circle_header_right">
							<view class="circle_header_right_top">
								<text>{{item?.realname}}</text>
								<button @click="handleDel(item)" class="circle_header_btn">
									<image src="http://qianxueapplet.suoeryun.com/delete.png">
									</image>
								</button>
							</view>
							<view class="circle_text">{{item?.content}}</view>
							<view class="circle_img">
								<template v-if="item?.dynamicType === '0'">
									<image :src="img" v-for="(img,index) in item?.images?.split(',')" :key="img"
										@click="handlePreview(item?.images,index)">
									</image>
								</template>
								<template v-else-if="item?.dynamicType === '1'">
									<view class="circle_video" @click="handleVideoPreview(item?.images)"
										:style="{height: Number(item.high)/3.5 + 'rpx',width:Number(item?.width)/3.5 +'rpx'}">
										<video :src="item?.images" :show-center-play-btn="false"
											:show-fullscreen-btn="false" :show-play-btn="false" :controls="false"
											:style="{height: Number(item.high)/3.5 + 'rpx',width:Number(item?.width)/3.5 +'rpx'}"></video>
										<image src="http://qianxueapplet.suoeryun.com/play.png"></image>
									</view>
								</template>
							</view>
							<view class="circle_header_right_bottom">
								<text>{{item?.fromToday}}编辑</text>
								<text v-if="item?.province">{{item?.province}}</text>
							</view>
							<view class="circle_tag" v-if="item?.activityName">
								<text>#{{item?.activityName}}</text>
							</view>
							<view class="circle_fun">
								<view @click="handleLike(item)">
									<image src="http://qianxueapplet.suoeryun.com/likeSelect.png"
										v-if="item?.izLike === '1'">
									</image>
									<image src="http://qianxueapplet.suoeryun.com/like.png" v-else>
									</image>
									<text>{{item?.likes}}</text>
								</view>
								<view @click="handleComment(item,index)">
									<image src="http://qianxueapplet.suoeryun.com/comments.png">
									</image>
									<text>{{item?.comment}}</text>
								</view>
								<view @click="handleShare(item)">
									<image src="http://qianxueapplet.suoeryun.com/forward.png">
									</image>
									<text>{{item?.relay}}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</template>
			<u-loadmore :status="status" @loadmore="scrolltolower" v-if="status !== 'nomore'"></u-loadmore>

			<!-- <view class="empty-img" v-if="tabCurrent === 0 ? !dataSouse.length : !dataSousePublished.length">
				<image mode="aspectFit" src="../../static/images/defaultimg/nodongtai.png"></image>
			</view> -->
			<u-empty v-if="tabCurrent === 0 ? !dataSouse.length : !dataSousePublished.length" marginTop="100"
				text="暂无动态" icon="http://qianxueapplet.suoeryun.com/dt.png"></u-empty>
		</scroll-view>

	</view>
	<!-- 评论 -->
	<comment ref="commentRef" @close="handleCommentClose"></comment>
	<!-- 分享 -->
	<customShare ref="shareRef"></customShare>
</template>

<script lang="ts" setup>
	import { ref, reactive, unref, onMounted, getCurrentInstance, onUnmounted } from 'vue';
	import comment from "@/components/comment.vue";
	import customShare from "@/components/customShare.vue";
	import { qxPlazaDynamicsList, qxPlazaDynamicsDel, likeOrUnLike } from '@/config/circle.api';

	const tabCurrent = ref(0);
	const triggered = ref(false);
	const scrollTop = ref(0);
	const status = ref('loadmore');
	// 草稿
	const dataSouse = ref([]);
	const pagination = reactive({ pageNo: 1, total: 0, pageSize: 10 });
	// 已发布
	const dataSousePublished = ref([]);
	const paginationPublished = reactive({ pageNo: 1, total: 0, pageSize: 10 });
	const commentRef = ref();
	const shareRef = ref();
	const commentIndex = ref(0);
	const { proxy } = getCurrentInstance();

	const tabList = [{
		id: 0,
		name: '草稿'
	}, {
		id: 1,
		name: '已发布'
	}];

	onMounted(() => {
		loadData();
		uni.$on('dynamicUpdate', _ => {
			loadData();
		})
	})

	onUnmounted(() => {
		uni.$off('dynamicUpdate');
	})

	/**
	 * 基地tab 点击
	 */
	function handleTabClick(item) {
		console.log(item, 'handleTabClick');
		tabCurrent.value = item?.id;
		if (item?.id === 0) {
			pagination.pageNo = 1;
			loadData();
		} else {
			paginationPublished.pageNo = 1;
			loadDataPublished();
		}
	}

	/**
	 * 加载数据
	 */
	async function loadData() {
		if (pagination.pageNo === 1) {
			dataSouse.value = [];
		}
		status.value = 'loading';
		const res = await qxPlazaDynamicsList({ ...pagination, publishStatus: '0', createBy: unref(proxy['vuex_user'])?.id });
		triggered.value = false;
		pagination.total = res?.total;
		dataSouse.value?.push(...res?.records);
		if (unref(dataSouse)?.length < pagination.total) {
			status.value = 'loadmore';
		} else {
			status.value = 'nomore';
		}
	}

	/**
	 * 滚动到底部操作
	 */
	function scrolltolower() {
		if (unref(dataSouse)?.length < pagination.total && (unref(dataSouse)?.length / pagination.pageSize == pagination.pageNo)) {
			pagination.pageNo++;
			loadData();
		}
	}

	/**
	 * 自定义下拉刷新被触发
	 */
	function onRefresh() {
		triggered.value = true;
		pagination.pageNo = 1;
		loadData();
	}

	/**
	 * 加载数据-已发布
	 */
	async function loadDataPublished() {
		if (paginationPublished.pageNo === 1) {
			dataSousePublished.value = [];
		}
		status.value = 'loading';
		const res = await qxPlazaDynamicsList({ ...paginationPublished, publishStatus: '1', createBy: unref(proxy['vuex_user'])?.id });
		triggered.value = false;
		paginationPublished.total = res?.total;
		dataSousePublished.value?.push(...res?.records);
		if (unref(dataSousePublished)?.length < paginationPublished.total) {
			status.value = 'loadmore';
		} else {
			status.value = 'nomore';
		}
	}

	/**
	 * 滚动到底部操作-已发布
	 */
	function scrolltolowerPublished() {
		console.log('lower', unref(dataSousePublished)?.length !== paginationPublished.total, unref(dataSouse)?.length, pagination.total);
		if (unref(dataSousePublished)?.length < paginationPublished.total) {
			paginationPublished.pageNo++;
			loadData();
		}
	}

	/**
	 * 自定义下拉刷新被触发-已发布
	 */
	function onRefreshPublished() {
		triggered.value = true;
		paginationPublished.pageNo = 1;
		loadData();
	}

	/**
	 * 删除
	 */
	function handleDel(item) {
		uni.showModal({
			content: '确认删除该动态吗？',
			confirmColor: '#FF943C',
			success: async function (res) {
				if (res.confirm) {
					paginationPublished.pageNo = 1;
					await qxPlazaDynamicsDel({ id: item?.id });
					if (unref(tabCurrent) === 0) {
						pagination.pageNo = 1;
						loadData();
					} else {
						paginationPublished.pageNo = 1;
						loadDataPublished();
					}
					loadData();
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		})
	}

	/**
	 * 点赞
	 */
	async function handleLike(item) {
		const res = await likeOrUnLike({ id: item?.id, izLike: item?.izLike === '1' ? '0' : '1' });
		item.izLike = res?.izLike;
		item.likes = res?.likes;
		uni.showToast({
			icon: 'none',
			title: res?.izLike === '1' ? '点赞成功' : '取消点赞'
		});
	}

	/**
	 * 评论
	 */
	function handleComment(item, index) {
		commentIndex.value = index;
		//type 1 活动 2图集 3视频
		commentRef.value.handleShow({ activityId: item?.id, num: item?.comment, belongId: item?.id, type: '1' });
	}

	/**
	 * 评论回调
	 */
	function handleCommentClose(num) {
		dataSousePublished.value[unref(commentIndex)]['comment'] = num;
	}

	/**
	 * 分享
	 */
	function handleShare(item) {
		shareRef.value.handleShow({ path: 'pages/circle/circleDetails', scene: `id=${item?.id}`, activityId: item?.id, });
	}


	/**
	 * 图片预览
	 */
	function handlePreview(imgs, index) {
		uni.previewImage({
			current: index,
			urls: imgs?.split(','),
		})
	}

	/**
	 * 视频预览
	 */
	async function handleVideoPreview(imgs) {
		uni.navigateTo({
			url: '/pages/circle/videoPreview?src=' + imgs,
		})
	}

	/**
	 * 编辑
	 */
	function handleEdit(item) {
		uni.navigateTo({
			url: '/pages/circle/releaseDynamics?id=' + item?.id,
		})
	}
</script>

<style lang="scss" scoped>
	.dynamic {
		::v-deep .u-tabs {
			background-color: #ffffff;
		}

		.dynamic_scroll_view {
			height: calc(100vh - 48px - 8rpx);
			margin-top: 8rpx;

			.circle_header_btn {
				width: 36rpx !important;
			}
		}
	}
</style>